package com.shy.task.quartz.job;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import org.quartz.Job;
import org.quartz.JobExecutionContext;

import com.shy.base.util.IpUtil;
import com.shy.base.util.IpWhiteCheckUtil;
import com.shy.base.util.StringUtils;
import com.shy.task.entity.TaskEntity;

import lombok.extern.slf4j.Slf4j;

/**
 * 普通的定时任务，继承此类的定时任务，到了执行时间自动执行
 *
 * @author shanhanyu
 * @date 2018/9/10 - 17:23
 */
@Slf4j
public abstract class AbstractCustomJob implements Job {

	@Override
	public void execute(JobExecutionContext jobExecutionContext) {
		String jobName = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("jobName");
		TaskEntity taskcfg = (TaskEntity) jobExecutionContext.getJobDetail().getJobDataMap().get("jobcfg");
		try {
			log.info("开始执行:[{}]", jobName);
			String workDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			//doExecute(workDate);
			String serverIp = IpUtil.getLocalIP();
			
			if(StringUtils.isNotEmpty(taskcfg.getServerNode()) && !IpWhiteCheckUtil.isPermited(serverIp, taskcfg.getServerNode())) {
				log.error(String.format("非指定节点，不执行任务:[%s]", jobName), serverIp);
			}else {
				doExecute(workDate, taskcfg);
			}
			//此处可以通过反射调用指定方法
			//TaskUtils.invokMethod(taskcfg);
		} catch (Exception e) {
			log.error(String.format("执行任务:[%s]失败", jobName), e);
		}
	}

	/**
	 * 执行业务逻辑
	 *
	 * @param workDate 执行日期
	 */
	public abstract void doExecute(String workDate);
	
	/**
	 * 执行业务逻辑
	 * @param workDate 执行日期
	 * @param 配置信息
	 */
	public abstract void doExecute(String workDate, TaskEntity taskcfg);
}
